package com.tanhua.sso.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsService {

    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

    //给sendCheckCode方法用的
    //在yml中配置了
//    @Autowired
//    private RestTemplate restTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SendSms sendSms;

    /**
     * 发送验证码
     * @param mobile
     * @return
     */
    public Map<String, Object> sendCheckCode(String mobile) {
        Map<String, Object> result = new HashMap<>(2);

        try {
            String redisKey = "CHECK_CODE_" + mobile;
            String value = this.redisTemplate.opsForValue().get(redisKey);
//            log.info("存储验证码到Redis, key: {}",
//                    redisKey);
/*log.info("存储验证码到Redis, key: {}, code: {}, 有效期: {}秒",
         redisKey, code, expireTime);*/
            //先看redis中有没有缓存这个手机号的验证码,判断验证码有没有存在
            if (StringUtils.isNotEmpty(value)) {
                result.put("code", 1);
                result.put("msg", "上一次发送的验证码还未失效");
                return result;
                //直接返回上一次的验证码:{"code":1;"msg":"上一次发送的验证码还未失效"}
            }

            //如果不存在,就是没有或者失效了
            String code = sendSms.sendSms(mobile);//调用发送短信验证码的逻辑
            if (null == code) {
                result.put("code", 2);
                result.put("msg", "发送短信验证码失败");
                return result;
                //{"code":2;"msg":"发送短信验证码失败"}
            }

            //能走到这里说明已经生成了code,code不是null
            //发送验证码成功
            result.put("code", 3);
            result.put("msg", "ok");

            //将验证码存储到Redis,2分钟后失效
            this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(2));
            return result;
            //{"code":3;"msg":"ok"}

        } catch (Exception e) {
            LOGGER.error("发送验证码出错！" + mobile, e);

            result.put("code", 4);
            result.put("msg", "发送验证码出现异常");
            return result;
        }
    }
}

